package com.woniu.jobhandler;

import com.woniu.entity.OrderDailyReport;
import com.woniu.mapper.OrderDailyReportMapper;
import com.woniu.mapper.OrderMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class DailyOrderReportJob {

    @Autowired
    private OrderMapper orderMapper; // 你的订单 Mapper

    @Autowired
    private OrderDailyReportMapper reportMapper; // 报表 Mapper

    /**
     * 每日凌晨执行：统计昨日订单数据
     */
    @XxlJob("dailytest")
    public void generateDailyReport() throws Exception {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        XxlJobHelper.log("开始生成 {} 的订单日报", yesterday);

        try {
            // 查询昨日数据
            int orderCount = orderMapper.countByDate(yesterday);
            BigDecimal totalAmount = orderMapper.sumAmountByDate(yesterday);
            BigDecimal refundAmount = orderMapper.sumRefundByDate(yesterday);
            int newUserOrders = orderMapper.countNewUserOrders(yesterday);

            // 构建报表对象
            OrderDailyReport report = new OrderDailyReport();

            report.setReportDate(java.sql.Date.valueOf(yesterday));

            report.setOrderCount(orderCount);
            report.setTotalAmount(totalAmount != null ? totalAmount : BigDecimal.ZERO);
            report.setRefundAmount(refundAmount != null ? refundAmount : BigDecimal.ZERO);
            report.setNewUserOrders(newUserOrders);


            // 保存或更新
            int rows = reportMapper.upsert(report);
            if (rows > 0) {
                XxlJobHelper.log("成功生成日报：订单数={}, 销售额={}", orderCount, report.getTotalAmount());
            } else {
                // 可能是更新失败，或没有匹配主键
                XxlJobHelper.log("日报生成失败，未更新任何记录");
            }

        } catch (Exception e) {
            XxlJobHelper.log("生成日报异常: " + e.getMessage());
            throw e; // 抛出异常，XXL-JOB 会标记为失败并可能触发重试
        }
    }
}